package com.dqhl.community.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.SortAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.Community;
import com.dqhl.community.util.CharacterParser;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;
import com.dqhl.community.util.PinyinComparator;
import com.dqhl.community.view.ClearEditText;
import com.dqhl.community.view.SideBar;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by cheng on 2016/9/8.
 * 定位小区
 */
public class LocationCommunityActivity extends BaseActivity {

    private ImageView ivTopBack;
    private TextView tvTopTitle;
    private ListView sortListView; //小区列表
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;

    private CharacterParser characterParser;
    private List<Community> SourceDateList = new ArrayList<>();
    private PinyinComparator pinyinComparator;

    private Community community; //选择的小区
    private String userId;
    private ClearEditText et_search;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location_community);

        initView();
        loadData();
    }

    /**
     * 获取小区列表
     */
    private void loadData() {
        showCustomLoadBar("加载中……");
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();

        RequestParams params = new RequestParams(Config.Api.community);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    List<Community> cellList = JSON.parseArray(data, Community.class);
                    Dlog.e("cellList:" + cellList);
                    if (!cellList.isEmpty() && cellList.size() > 0) {
                        for (int i = 0; i < cellList.size(); i++) {
                            Community community = new Community();
                            community.setName(cellList.get(i).getName());
                            community.setId(cellList.get(i).getId());
                            //汉字转换成拼音
                            String pinyin = characterParser.getSelling(cellList.get(i).getName());
                            String sortString = pinyin.substring(0, 1).toUpperCase();

                            // 正则表达式，判断首字母是否是英文字母
                            if (sortString.matches("[A-Z]")) {
                                community.setSortLetters(sortString.toUpperCase());
                            } else {
                                community.setSortLetters("#");
                            }
                            SourceDateList.add(community);
                        }
                        Dlog.e("SourceDateList:" + SourceDateList);

                        pinyinComparator = new PinyinComparator();
                        // 根据a-z进行排序源数据
                        Collections.sort(SourceDateList, pinyinComparator);
                        adapter = new SortAdapter(LocationCommunityActivity.this, SourceDateList);
                        sortListView.setAdapter(adapter);
                    }else {
                        toast(R.string.error_no_info);
                    }

                }else {
                    toast(R.string.error_server_connection);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                toast(R.string.error_net_connection);
                adapter = new SortAdapter(LocationCommunityActivity.this, SourceDateList);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    private void initView() {
//        SourceDateList = filledData(getResources().getStringArray(R.array.date));

        userId = getIntent().getStringExtra("user_id");
        Dlog.e("传过来的userid:" + userId);

        ivTopBack = (ImageView) findViewById(R.id.iv_top_back);
        ivTopBack.setVisibility(View.VISIBLE);
        ivTopBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tvTopTitle = (TextView) findViewById(R.id.tv_top_title);
        tvTopTitle.setText("定位所在小区");
        sideBar = (SideBar) findViewById(R.id.sidebar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        sortListView = (ListView) findViewById(R.id.lv_cell);
        et_search = (ClearEditText) findViewById(R.id.et_search);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }
            }
        });

        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
                community = (Community) adapter.getItem(i);
                Dlog.e("选择了：" + community.getName() + ";id:" + community.getId());
                // 跳转到补全信息页面
                Bundle bundle = new Bundle();
                bundle.putString("community_name", community.getName());
                bundle.putString("community_id", community.getId());
                bundle.putString("user_id", userId);
                overlay(ComplementInfoActivity.class, bundle);
            }
        });

        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<Community> filledData(String[] date) {
        List<Community> mSortList = new ArrayList<Community>();

        for (int i = 0; i < date.length; i++) {
            Community community = new Community();
            community.setName(date[i]);
            //汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                community.setSortLetters(sortString.toUpperCase());
            } else {
                community.setSortLetters("#");
            }

            mSortList.add(community);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<Community> filterDateList = new ArrayList<Community>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (Community sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

}
